﻿#include "MailSender.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QSslSocket>
#include <QDebug>


MailSender::MailSender(QObject *parent)
    : QObject{parent}
{
    connect(&m_net, &QNetworkAccessManager::finished, this, &MailSender::onReply);


    qDebug() << "[OpenSSL Info]   [Supported]:" << QSslSocket::supportsSsl() <<
        ", [BuildVersion]:" << QSslSocket::sslLibraryBuildVersionString() <<
        ", [RealVersion]:" << QSslSocket::sslLibraryVersionString();

}

void MailSender::setReceiverMail(const QString &mail)
{
    m_recevier = mail;
}

void MailSender::setSubject(const QString &subject)
{
    m_subject = subject;
}

void MailSender::setTitle(const QString &title)
{
    m_title = title;
}

void MailSender::setHtml(const QString &html)
{
    m_html = html;
}

void MailSender::addAttachment(const QString &name, const QByteArray &content)
{
    MailAttachment attachment = { name, content };
    m_attachments.append(attachment);
}

void MailSender::clearAttachments()
{
    m_attachments.clear();
}

void MailSender::send()
{
    // 使用 ColaMail API
    QJsonObject payload;
    payload["ColaKey"] = "gFxasPGt4zJN6L1763541169120AR1IAKusU8";
    payload["smtpCode"] = "ogqesogryajddbeg";
    payload["smtpEmail"] = "gistudio@foxmail.com";
    payload["smtpCodeType"] = "qq";

    payload["tomail"] = m_recevier;
    payload["fromTitle"] = m_title;
    payload["subject"] = m_subject;
    payload["content"] = m_html;

    QJsonDocument doc(payload);

    QNetworkRequest req(QUrl("https://luckycola.com.cn/tools/customMail"));
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    m_net.post(req, doc.toJson());
}

void MailSender::onReply(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        emit finished(true, reply->readAll());
    } else {
        emit finished(false, reply->readAll());
    }

    reply->deleteLater();
}
